﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DACU.Tools;
using DACU.VkontakteApi.Base;
using DACU.VkontakteApi.Enums;

namespace DACU.VkontakteApi.Collections
{
	public class VKAudioCollection:List<VKAudio>
	{
		public DateTime DownloadTimeStamp { get; set; }
		public string DownloadTime
		{
			get { return DownloadTimeStamp.ToString(); }
			set
			{
				DateTime time;
				if (DateTime.TryParse(value, out time))
					DownloadTimeStamp = time;
			}

		}

		public VKAudioCollection()
		{
		}

		public VKAudioCollection(IEnumerable<VKAudio> collection)
			: base(collection)
		{
		}

		public VKAudioCollection(IEnumerable<VKAudio> collection,DateTime timestamp)
			: base(collection)
		{
			DownloadTimeStamp = timestamp;
		}

		public bool IsEmpty
		{
			get { return Count < 1; }
		}

		public static VKAudioCollection ParseResponse(string response, VKResponseFormats format)
		{
			if(String.IsNullOrWhiteSpace(response))throw new ArgumentNullException("reponse");
			switch (format)
			{
				case VKResponseFormats.JSON:
					throw new NotImplementedException();
				case VKResponseFormats.XML:
					return ParseXml(XElement.Parse(response, LoadOptions.None));
				default:
					return new VKAudioCollection{DownloadTimeStamp=DateTime.UtcNow};
			}
		}

		public static VKAudioCollection ParseXml(XElement response)
		{
			if(response==null || response.IsEmpty)throw new ArgumentNullException("response");
			var audios = response.Elements("audio");
			if (audios == null || audios.Count() < 1) throw new ArgumentNullException("response");
			return audios.Select(VKAudio.ParseXml).ToAudioCollection(DateTime.UtcNow);
		}
	}
}
